package com.qf.controller;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.github.wxpay.sdk.WXPayUtil;
//import com.qf.server.WebSocketServer;
import com.qf.server.WebSocketServer;
import com.qf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：Xx凯丶
 * 时间：2022/4/25 10:32
 */
@RestController
@CrossOrigin
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private OrderService orderService;
    @PostMapping("/success")
    public String callback(HttpServletRequest request) throws Exception{
        ServletInputStream inputStream = request.getInputStream();

        StringBuffer buffer = new StringBuffer();
        byte[] bs = new byte[1024];
        int len = -1;
        while((len = inputStream.read(bs))!=-1){
            buffer.append(new String(bs,0,len));
        }
        String s = buffer.toString();
        Map<String, String> msgMap = WXPayUtil.xmlToMap(s);
        if("SUCCESS".equals( msgMap.get("result_code") ) &&
                "SUCCESS".equals( msgMap.get("return_code") )){
            //付款成功
            String orderId = msgMap.get("out_trade_no");
            //根据订单id修改数据库订单状态为 "已完成"
            boolean i = orderService.changeOrder(orderId);
            WebSocketServer.sendMsg(orderId,"SUCCESS");
            //响应微信支付平台
            HashMap<String,String> resp = new HashMap<>();
            resp.put("return_code","success");
            resp.put("return_msg","OK");
            resp.put("appid",msgMap.get("appid"));
            resp.put("result_code","success");
            return WXPayUtil.mapToXml(resp);
        }
        return null;
    }

}
